﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using QianBuo.Lottery.Web.Areas.Manage.Models.Site;
using Code.Models;
using Code.Commen;
using QianBuo.Lottery.Web.Models;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    public class SiteController : BaseController
    {
      
        #region 系统设置
        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult Option()
        {
            var model = new OptionModel();
            model.Options = new ModelNameValue<Option_Site_Key, NameValueItem<string, string>>(
                CacheManage.OptionSite.Where(p => !p.Key.ShowOtherPage()).OrderBy(p => (int)p.Key).ToNameValue(p => p.Key, p => new NameValueItem<string, string>(p.Value.Key, p.Value.Value)));
            model.OldOptions = model.Options;
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult Option(OptionModel model)
        {
            var form = Request.Form;
            var som = new SiteManage();
            DES des = new DES();
            var upitems = new NameValue<object, object>();
            var inserts = new List<object>();
            model.Options = new ModelNameValue<Option_Site_Key, NameValueItem<string, string>>();
            foreach (var item in model.OldOptions)
            {
                var value = form[item.Value.Key];
                value = string.IsNullOrEmpty(value) ? null : value;
                var detail = item.Key.GetDetail();
                if (detail.Type == ControlType.HtmlBox)
                    continue;
                if (detail.Type == ControlType.CheckBox)
                    value = (value == null ? false : value.IndexOf("true", StringComparison.CurrentCultureIgnoreCase) >= 0).ToString();
                model.Options.Add(item.Key, new NameValueItem<string, string> { Key = item.Value.Key, Value = value });
                if (!detail.IsNull && string.IsNullOrEmpty(value))
                {
                    ModelState.AddModelError(item.Value.Key, "不能为空");
                    continue;
                }
                if (!string.IsNullOrEmpty(value) && !detail.Valid(value))
                {
                    ModelState.AddModelError(item.Value.Key, "格式不正确");
                    continue;
                }
                if ((!string.IsNullOrEmpty(value) && string.IsNullOrEmpty(item.Value.Value)) || item.Value.Value != value)
                {
                    if (detail.Type == ControlType.Password && value != null)
                        value = des.EncryptString(value, Salt.Password.GetDesSalt().Key, Salt.Password.GetDesSalt().Value);
                    else if (detail.Type == ControlType.Password)
                        continue;

                    if (CacheManage.DBKeys.Contains(item.Key))
                    {
                        var update = new NameValue<string, object> { { "Value", string.IsNullOrEmpty(value) ? null : item.Key.ToObject(value).ToString() } };
                        var where = new NameValue<string, object> { { "Key", item.Value.Key } };
                        upitems.Add(update, where);
                    }
                    else
                        inserts.Add(new { item.Value.Key, Value = string.IsNullOrEmpty(value) ? null : item.Key.ToObject(value).ToString() });
                }
            }

            string msg = null;
            int count = 0;
            if (ModelState.IsValid)
            {
                if (upitems.Count == 0 && inserts.Count == 0)
                    msg = "没有要保存的项！";
                else
                {
                    som.BeginTransaction();
                    som.Update(upitems);
                    som.Insert(inserts.ToArray());
                    count = som.ExecuteTransaction();
                    if (count > 0)
                    {
                        msg = "已保存成功！";
                        CacheManage.IsLoadOptionSite = true;
                    }
                    else if (count < 0)
                        msg = "保存失败！请稍后再重新操作。";
                }
            }

            if (Request.IsAjaxRequest())
            {
                var errors = ModelState.Where(p => p.Value.Errors.Count > 0).Select(p => new { Name = p.Key, Error = p.Value.Errors.First().ErrorMessage }).ToArray();
                return Json(new { msg, errors, count }, JsonRequestBehavior.AllowGet);
            }
            ViewData["msg"] = count > 0 ? "".Redirect(msg) : msg.AlertOffPage();
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult OptionHtml(Option_Site_Key id)
        {
            if (id == Option_Site_Key.Site_Lottery_BackMoneyRatio)
                return RedirectToAction("SetBackMoneyRatio", new { act = "Option", cont = "Site" });
            var model = new OptionHtmlModel();
            var option = CacheManage.OptionSite[id];
            model.Key = id;
            model.Value = option.Value;
            return View(model);
        }

        [HttpPost, ValidateInput(false)]
        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult OptionHtml(Option_Site_Key id, OptionHtmlModel model)
        {
            var dd = id.GetDetail();
            var val = true;
            if (!dd.IsNull && !string.IsNullOrEmpty(model.Value))
                val = dd.Valid(model.Value);
            if (!val)
                ModelState.AddModelError("Error", "格式不正确");
            else
            {
                var SM = new SiteManage();
                int rs = SM.Update(new { model.Value }, new { Key = id.ToString() });
                if (rs != 1)
                    ModelState.AddModelError("Error", "系统错误，请稍后再试！");
                else
                {
                    ViewData["msg"] = "保存成功！".AlertOffPage();
                    CacheManage.IsLoadOptionSite = true;
                }
            }
            return View(model);
        }

        public ActionResult SetBackMoneyRatio()
        {
            SetBackMoneyRatioModel model = new SetBackMoneyRatioModel();
            var sm = new SiteManage();
            model.Options = sm.GetBackMoneyRatios().ToArray();
            return View(model);
        }
        [HttpPost]
        public ActionResult SetBackMoneyRatio(SetBackMoneyRatioModel model)
        {
            var sm = new SiteManage();
            var old = sm.GetBackMoneyRatios();
            old.Each((p, i) =>
            {
                var item = model.Options[i];
                item.key = p.key;
                item.WinModelID = p.WinModelID;
            });
            var list = model.Options.GroupBy(p => p.key);
            int error = 0;
            foreach (var item in list)
            {
                if (item.Select(p => { double v; return string.IsNullOrEmpty(p.Value) || double.TryParse(p.Value, out v); }).Contains(false))
                    continue;
                var count = sm.Update(new { value = string.Join(",", item.Select(p => p.WinModelID + "_" + p.Value).ToArray()) }, new { key = item.Key.ToString() });
                if (count < 0)
                    error++;
            }
            if (error == 0)
                ViewData["msg"] = "操作成功!".AlertOffPage();
            else
                ViewData["msg"] = "操作失败,请稍后再试!".AlertOffPage();
            return View(model);
        }
        #endregion
        #region 清除数据
        [Authorize(Roles = "Manager_Site_ClearData")]
        public ActionResult ClearData()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_ClearData")]
        public ActionResult ClearData(ClearDataModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var SM = new SiteManage();
                    int rs=SM.ClearData(model.Date.Value, model.Pwd);
                    if (rs < 0)
                        throw new AppException();
                    ViewData["msg"] = Url.Action("ClearData").Redirect("成功清除数据 "+rs+" 条");
                }
                catch (ValidateException e)
                { ModelState.AddModelError(e.Source ?? "Error", e.Message); }
                catch (Exception)
                { ViewData["msg"] = "系统错误，请稍后再试!".AlertOffPage(); }
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_ClearData")]
        public ActionResult LoginLog(LoginLogModel model)
        {
            if (model == null)
                model = new LoginLogModel();
            if (model.Serch == null)
                model.Serch = new LoginLogSerchModel();
            if (model.Page < 1)
                model.Page = 1;
            if (model.PageSize < 1)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);;

            var types = (Enum.GetValues(typeof(LoginLogType)) as LoginLogType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString(), Selected = p == model.Serch.Type }).ToList();
            types.Insert(0, new SelectListItem { Text = "所有", Value = "", Selected = !model.Serch.Type.HasValue });
            model.Types = types;
            var tp = new LoginResult[] { LoginResult.Normal, LoginResult.Locked, LoginResult.PWDError };
            var results = tp.Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString(), Selected = p == model.Serch.Result }).ToList();
            results.Insert(0, new SelectListItem { Text = "所有", Value = "", Selected = !model.Serch.Result.HasValue });
            model.Results = results;
           
            var CM = new CommenManage<LoginLog_V>();
            var data = CM.Select(s => s);
            if (model.Serch.StartTime.HasValue)
                data = data.Where(p => p.LoginTime >= model.Serch.StartTime);
            if (model.Serch.EndTime.HasValue)
                data = data.Where(p => p.LoginTime < model.Serch.EndTime.Value.AddDays(1));
            if (model.Serch.Type.HasValue)
                data = data.Where(p => p.LoginType == (short)model.Serch.Type);
            if (model.Serch.Result.HasValue)
                data = data.Where(p => p.LoginResult == (short)model.Serch.Result);
            if (!string.IsNullOrEmpty(model.Serch.LoginName))
                data = data.Where(p => p.LoginName == model.Serch.LoginName);
            if (!string.IsNullOrEmpty(model.Serch.LoginIP))
                data = data.Where(p => p.LoginIP == model.Serch.LoginIP);
            model.SumCount = data.Count();
            model.Logs = data.OrderByDescending(p => p.LoginTime).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize).ToArray();
            
            return View("LoginLog", model);
        }
        
        [HttpPost]
        [Authorize(Roles = "Manager_Site_ClearData")]
        [QianBuo.Lottery.Web.Commen.MultiButton(Name = "ClearData")]
        public ActionResult LoginLog(ClearDataModel model)
        {
            ViewData["Date"] = string.Format("{0:yyyy-MM-dd}",model.Date);
            if (ModelState.IsValid)
            {
                try
                {
                    var SM = new SiteManage();
                    int rs = SM.LoginLogClear(model.Date.Value, model.Pwd);
                    if (rs < 0)
                        throw new AppException();
                    ViewData["msg"] = Url.Action("LoginLog").Redirect("成功清除数据 " + rs + " 条");
                }
                catch (ValidateException e)
                { ModelState.AddModelError(e.Source ?? "Error", e.Message); }
                catch (Exception)
                { ViewData["msg"] = "系统错误，请稍后再试!".AlertOffPage(); }
            }
            return LoginLog(new LoginLogModel());
        }
        #endregion

        #region 支付接口设置
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult Pay(PayType? id)
        {
            if (id.HasValue)
            {
                var rs = SetPay(id.Value);
                if (!(rs is EmptyResult))
                    return rs;
            }

            var model = new PayOptionModel();

            var SM = new SiteManage();
            var tp=(Enum.GetValues(typeof(PayType)) as PayType[]).Select(p => p.GetDetail())
                .Select(p => new PayOptionItem{Pay = p.PayType,Name = p.Name,MemberID = p.MumberID,Enable = p.Enable})
                .ToNameValue(p => p.Pay, p => p);
            model.Pays = new ModelNameValue<PayType, PayOptionItem>(tp);
                
            return View(model);
        }

        [NonAction]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult SetPay(PayType type)
        {
            switch (type)
            {
                case PayType.YeePay:
                    return YeePay();
                default:
                    ViewData["msg"] = ("无法设置" + type.GetName()).AlertOffPage();
                    return new EmptyResult();
            }
        }

        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult YeePay()
        {
            var tp=PayType.YeePay.GetDetail();
            var model = new YeePayModel
            {
                Name = tp.Name,
                MemberID = tp.MumberID,
                Enable = tp.Enable,
                Addr = tp.Addr,
                Key = CacheManage.OptionSite[Option_Site_Key.Site_Pay_YeePay_Key].Value
            };
            return View("YeePay",model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult YeePay(YeePayModel model)
        {
            model.Enable = model.Enable ?? false;
            model.Addr = CacheManage.OptionSite[Option_Site_Key.Site_Pay_YeePay_ReqUrl].Value;
            if (model.Enable.Value)
            {
                if (string.IsNullOrEmpty(model.Addr))
                    ModelState.AddModelError("Addr", "启用状态不能为空");
                if (string.IsNullOrEmpty(model.Key))
                    ModelState.AddModelError("Key", "启用状态不能为空");
                if (string.IsNullOrEmpty(model.MemberID))
                    ModelState.AddModelError("MemberID", "启用状态不能为空");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    var SM = new SiteManage();
                    int rs = SM.YeePayOption(model.Enable.Value, model.MemberID, model.Key, model.Addr, model.Pwd);
                    if (rs < 0)
                        throw new AppException();
                    
                    ViewData["msg"] = Url.Action("Pay").Redirect("保存成功");
                    CacheManage.IsLoadOptionSite = true;
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.Source, e.Message);
                }
                catch (Exception)
                {
                    ModelState.AddModelError("Error", "系统错误，请稍后再试"); 
                }
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult AliPay()
        {
            var tp = PayType.AliPay.GetDetail();
            var model = new AliPayModel
            {
                Name=tp.Name,
                MemberID=tp.MumberID,
                Enable=tp.Enable,
                Addr=tp.Addr,
                Key=CacheManage.OptionSite[Option_Site_Key.Site_Pay_AliPay_Key].Value,
                Email=CacheManage.OptionSite[Option_Site_Key.Site_Pay_AliPay_Email].Value,
                MemberName=CacheManage.OptionSite[Option_Site_Key.Site_Pay_AliPay_Manual_MemberName].Value
            };
            return View("AliPay",model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult AliPay(AliPayModel model)
        {
            model.Enable = model.Enable ?? false;
            model.Addr = CacheManage.OptionSite[Option_Site_Key.Site_Pay_AliPay_ReqUrl].Value;
            if (model.Enable.Value)
            {
                if (string.IsNullOrEmpty(model.Addr))
                    ModelState.AddModelError("Addr", "启用状态不能为空");
                if (string.IsNullOrEmpty(model.Key))
                    ModelState.AddModelError("Key", "启用状态不能为空");
                if (string.IsNullOrEmpty(model.MemberID))
                    ModelState.AddModelError("MemberID", "启用状态不能为空");
                if (string.IsNullOrEmpty(model.Email))
                    ModelState.AddModelError("Email", "启用状态不能为空");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    var SM = new SiteManage();
                    int rs = SM.AliPayOption(model.Enable.Value, model.MemberID, model.Key, model.Addr, model.Pwd,model.Email,model.MemberName);
                    if (rs < 0)
                        throw new AppException();

                    CacheManage.IsLoadOptionSite = true;
                    ViewData["msg"] = Url.Action("Pay").Redirect("保存成功");
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.Source, e.Message);
                }
                catch (Exception)
                {
                    ModelState.AddModelError("Error", "系统错误，请稍后再试");
                }
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult TenPay()
        {
            var tp = PayType.TenPay.GetDetail();
            var model = new TenPayModel
            {
                Name = tp.Name,
                MemberID = tp.MumberID,
                Enable = tp.Enable,
                Addr = tp.Addr,
                Key = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPay_Key].Value,
                MemberName=CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPay_Manual_MemberName].Value
            };
            return View("TenPay", model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult TenPay(TenPayModel model)
        {
            model.Enable = model.Enable ?? false;
            model.Addr = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPay_ReqUrl].Value;
            if (model.Enable.Value)
            {
                if (string.IsNullOrEmpty(model.Addr))
                    ModelState.AddModelError("Addr", "请输入接口地址");
                if (string.IsNullOrEmpty(model.Key))
                    ModelState.AddModelError("Key", "请输入商户密钥");
                if (string.IsNullOrEmpty(model.MemberID))
                    ModelState.AddModelError("MemberID", "请输入商户编号");
                if (string.IsNullOrEmpty(model.MemberName))
                    ModelState.AddModelError("MemberName", "请输入商户名称");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    var SM = new SiteManage();
                    int rs = SM.TenPayOption(model.Enable.Value, model.MemberID, model.Key, model.Addr, model.Pwd,model.MemberName);
                    if (rs < 0)
                        throw new AppException();

                    ViewData["msg"] = Url.Action("Pay").Redirect("保存成功"); 
                    CacheManage.IsLoadOptionSite = true;
                }
                catch (ValidateException e)
                {
                    ModelState.AddModelError(e.Source, e.Message);
                }
                catch (Exception)
                {
                    ModelState.AddModelError("Error", "系统错误，请稍后再试"); 
                }
            }
            return View(model);
        }
        #region 工行转账设置
        
       
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult ICBC_Manual()
        {
            var tp = PayType.ICBC_Manual.GetDetail();
            double tmp;
            var model = new ICBC_ManualModel
            {
                Name = tp.Name,
                MemberID = tp.Key,
                Enable = tp.Enable,
                MemberName=tp.MumberID,
                Memo = tp.Addr,
                ChargeRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_ChargeRatio].ToDouble(out tmp) ? tmp : null as double?,
                MinCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?,
                MaxCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?,
             
            };
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult ICBC_Manual(ICBC_ManualModel model)
        {
            model.Enable = model.Enable ?? false;
            if (model.Enable.Value)
            {
                if ((!string.IsNullOrEmpty(model.MemberID)) && (!string.IsNullOrEmpty(model.MemberName))
                    || (!string.IsNullOrEmpty(model.AliPayMemberID)) && (!string.IsNullOrEmpty(model.AliPayMemberName))
                    || (!string.IsNullOrEmpty(model.TenPayMemberID)) && (!string.IsNullOrEmpty(model.TenPayMemberName))
                    )
                {
                    try
                    {
                        var SM = new SiteManage();
                        int rs = SM.ICBC_ManualOption(model.Enable.Value, model.MemberName, model.MemberID, model.Memo, model.Pwd, model.ChargeRatio, model.MinCharge, model.MaxCharge);
                        if (rs < 0)
                            throw new AppException();

                        ViewData["msg"] = Url.Action("Pay").Redirect("保存成功");
                        CacheManage.IsLoadOptionSite = true;
                    }
                    catch (ValidateException e)
                    {
                        ModelState.AddModelError(e.Source, e.Message);
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("Error", "系统错误，请稍后再试");
                    }
                }
            }
            return View(model);
        }
       #endregion


        #region 支付宝转账设置
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult AliPays_Manual()
        {
            var tp = PayType.AliPays_Manual.GetDetail();
            double tmp;
            var model = new Alipays_ManualModel
            {
                Name = tp.Name,
                MemberID = tp.Key,
                Enable = tp.Enable,
                MemberName = tp.MumberID,
                Memo = tp.Addr,
                ChargeRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_ChargeRatio].ToDouble(out tmp) ? tmp : null as double?,
                MinCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?,
                MaxCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?,

            };
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult AliPays_Manual(Alipays_ManualModel model)
        {
            model.Enable = model.Enable ?? false;
            if (model.Enable.Value)
            {
                if ((!string.IsNullOrEmpty(model.MemberID)) && (!string.IsNullOrEmpty(model.MemberName))
                    || (!string.IsNullOrEmpty(model.AliPayMemberID)) && (!string.IsNullOrEmpty(model.AliPayMemberName))
                    || (!string.IsNullOrEmpty(model.TenPayMemberID)) && (!string.IsNullOrEmpty(model.TenPayMemberName))
                    )
                {
                    try
                    {
                     
                        var SM = new SiteManage();
                        int rs = SM.Alipas_ManualOption(model.Enable.Value, model.MemberName, model.MemberID, model.Memo, model.Pwd, model.ChargeRatio, model.MinCharge, model.MaxCharge);
                        if (rs < 0)
                            throw new AppException();

                        ViewData["msg"] = Url.Action("Pay").Redirect("保存成功");
                        CacheManage.IsLoadOptionSite = true;
                    }
                    catch (ValidateException e)
                    {
                        ModelState.AddModelError(e.Source, e.Message);
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("Error", "系统错误，请稍后再试");
                    }
                }
            }
            return View(model);
        }


        #endregion
        #region 财付通转账设置
         [Authorize(Roles = "Manager_Site_Pay")]
        public ActionResult TenPays_Manual()
        {
            var tp = PayType.TenPays_Manual.GetDetail();
            double tmp;
            var model = new TenPays_ManualModel
            {
                Name = tp.Name,
                MemberID = tp.Key,
                Enable = tp.Enable,
                MemberName = tp.MumberID,
                Memo = tp.Addr,
                ChargeRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_ChargeRatio].ToDouble(out tmp) ? tmp : null as double?,
                MinCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?,
                MaxCharge = CacheManage.OptionSite[Option_Site_Key.Site_Pay_TenPays_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?,

            };
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_Pay")]
         public ActionResult TenPays_Manual(TenPays_ManualModel model)
        {
            model.Enable = model.Enable ?? false;
            if (model.Enable.Value)
            {
                if ((!string.IsNullOrEmpty(model.MemberID)) && (!string.IsNullOrEmpty(model.MemberName))
                    || (!string.IsNullOrEmpty(model.AliPayMemberID)) && (!string.IsNullOrEmpty(model.AliPayMemberName))
                    || (!string.IsNullOrEmpty(model.TenPayMemberID)) && (!string.IsNullOrEmpty(model.TenPayMemberName))
                    )
                {
                    try
                    {
                        var SM = new SiteManage();
                        int rs = SM.TenPay_ManualOption(model.Enable.Value, model.MemberName, model.MemberID, model.Memo, model.Pwd, model.ChargeRatio, model.MinCharge, model.MaxCharge);
                        if (rs < 0)
                            throw new AppException();

                        ViewData["msg"] = Url.Action("Pay").Redirect("保存成功");
                        CacheManage.IsLoadOptionSite = true;
                    }
                    catch (ValidateException e)
                    {
                        ModelState.AddModelError(e.Source, e.Message);
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("Error", "系统错误，请稍后再试");
                    }
                }
            }
            return View(model);
        }
        #endregion


        #endregion

        #region 奖金、元角模式设置
        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult Model()
        {
            var model = new ConsumptionModel();
            model.Ratios = CacheManage.Ratio.Values.Select(p => new RatioItem
            {
                ID = p.ID,
                Name=p.Name,
                RadixMoney = (double)p.RadixMoney,
                BackMoneyDifference = (double)p.BackMoneyDifference * 100,
                Enable = (p.State == (short)ConsumeRatioState.Normal)
            }).OrderBy(p=>p.ID).ToArray();
            model.WinModels = CacheManage.WinModel.Values.Select(p => new WinModelItem
            {
                ID = p.ID,
                Name = p.Name,
                Enable = p.State == (short)WinMoneyModelState.Normal
            }).OrderBy(p=>p.ID).ToArray();

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Site_SysOption")]
        public ActionResult Model(ConsumptionModel model)
        {
            if (ModelState.IsValid)
            {
                var SM = new SiteManage();
                SM.BeginTransaction();
                foreach (var item in model.Ratios)
                    SM.Update<ConsumptionRatio>(new { State = (short)(item.Enable ? ConsumeRatioState.Normal : ConsumeRatioState.Locked), BackMoneyDifference = item.BackMoneyDifference / 100, item.RadixMoney, item.Name }, new { item.ID });
                int count = 0;
                foreach (var item in model.WinModels)
                {
                    if (item.Enable == false)
                    {
                        count++;
                    }
                    
                }
                if (count == 3)
                {

                    ViewData["msg"] = Url.Action("Model").Redirect("必须启用一个模式！");
                   
                    return View(model);
                }
                foreach (var item in model.WinModels)
                {
                    SM.Update<WinMoneyModel>(new { State = (short)(item.Enable ? WinMoneyModelState.Normal : WinMoneyModelState.Locked), item.Name }, new { item.ID });
                }
                int rs = SM.ExecuteTransaction();
                if (rs > 0)
                {
                    ViewData["msg"] = Url.Action("Model").Redirect("保存成功！");
                    CacheManage.IsLoadRatio = true;
                    CacheManage.IsLoadWinModel = true;
                }
                else
                    ViewData["msg"] = "保存失败，请稍后再试".AlertOffPage();
            }
            return View(model);
        }

        #endregion

        #region 公告管理
        [Authorize(Roles = "Manager_Site_Notice")]
        public ActionResult Notice(NoticeModel model)
        {
            if (model.PageSize < 1)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15);;
            if (model.Page < 1)
                model.Page = 1;
            model.States = (Enum.GetValues(typeof(NoticeState)) as NoticeState[]).Select(p => new SelectListItem {Text=p.GetName(),Value=p.ToString() }).ToList();
            model.States.Insert(0, new SelectListItem { Text = "状态", Value = string.Empty });
            if (ModelState.IsValid)
            {
                var CM = new CommenManage<Notice>();
                var notices = CM.Select(s => s);
                if (model.Serch.StartTime.HasValue)
                    notices = notices.Where(p => p.AddTime >= model.Serch.StartTime.Value.Date);
                if (model.Serch.EndTime.HasValue)
                    notices = notices.Where(p => p.AddTime < model.Serch.EndTime.Value.Date.AddDays(1));
                if (model.Serch.State.HasValue)
                    notices = notices.Where(p => p.State == (short)model.Serch.State.Value);
                if (!string.IsNullOrEmpty(model.Serch.Title))
                    notices = notices.Where(p => p.Title.Contains(model.Serch.Title));
                model.SumCount = notices.Count();
                if (model.SumCount > 0)
                {
                    model.Notices = notices.Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize)
                        .ToArray().Select(p=>new NoticeItem{
                            ID=p.ID,AddTime=p.AddTime,State=(NoticeState)p.State,Message=p.Message,Title=p.Title,HighLight=p.HighLight
                        }).ToArray();
                }
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Site_Notice")]
        public ActionResult EditNotice(long? id)
        {
            var model = new EditNoticModel();
            model.States = new ModelNameValue<NoticeState, string>
                ((Enum.GetValues(typeof(NoticeState)) as NoticeState[]).ToNameValue(p => p, p => p.GetName()));
            if (id.HasValue)
            {
                var CM = new CommenManage<Notice>();
                var item = CM.Select(s => s.FirstOrDefault(p => p.ID == id));
                if(item==null)
                    return Content("<script>alert('不存在该公告！');location.href='" + Url.Action("Notice") + "'</script>");

                model.Item = new NoticeItem
                 {
                     ID = item.ID,
                     AddTime = item.AddTime,
                     State = (NoticeState)item.State,
                     Message = item.Message,
                     Title = item.Title,
                     HighLight = item.HighLight
                 };
            }
            else
            {
                model.Item = new NoticeItem() { ID = -1 };
                model.IsNew = true;
            }
            return View(model);
        }

        [HttpPost, ValidateInput(false)]
        [Authorize(Roles = "Manager_Site_Notice")]
        public ActionResult EditNotice(EditNoticModel model)
        {
            if (ModelState.IsValid)
            {
                var obj = new { model.Item.Title, State = (short)model.Item.State, model.Item.HighLight, model.Item.Message };
                var CM = new CommenManage<Notice>();
                int rs = 0;
                if (model.IsNew)
                    rs = CM.Insert(obj);
                else
                    rs = CM.Update(obj, new { model.Item.ID });
                CacheManage.IsLoadNotices = rs == 1;
                if (rs == 1 && model.IsNew && model.Continue)
                    return Content(string.Format("<script>alert('{0}');location.href='{1}'</script>", "新增成功", Url.Action("EditNotice", new { returnurl = Request["returnurl"] })));
                else if (rs == 1)
                    return Content(string.Format("<script>alert('{0}');location.href='{1}'</script>", (model.IsNew ? "新增" : "更新") + "成功", Request["returnurl"] ?? Url.Action("Notice")));
                else
                    ViewData["msg"] = "保存失败，请稍后再试！".AlertOffPage();
            }
            return View(model);
        }


        [Authorize(Roles = "Manager_Site_Notice")]
        public ActionResult DeleteNotice(long id)
        { 
            var CM=new CommenManage<Notice>();
            int rs = CM.Delete(new { id }); 
            CacheManage.IsLoadNotices = rs == 1;
            string msg = rs == 1 ? "删除成功！" : "不存在该公告！";
            if (Request.IsAjaxRequest())
            {
                return Json(new { rs, msg },JsonRequestBehavior.AllowGet);
            }
            return Content(string.Format("<script>alert('{0}');location.href='{1}'</script>", msg, Request["returnurl"]??Url.Action("Notice")));
        }
        #endregion
    }
}
